<?php


namespace app\admin\system\controller;


use app\admin\system\service\AdminService;
use app\model\SysAdmin;
use app\model\SysRole;
use support\exception\BadException;
use support\utils\RandomUtil;
use think\facade\Db;

class AdminController extends BaseController
{
    protected $model = SysAdmin::class;

    protected $noNeedRight = [
        'loginUserInfo',
    ];

    public function loginUserInfo()
    {
        $uid = request()->uid;
        $user = $this->getModel()->where([
            'id' => $uid
        ])->withoutField(['password', 'salt'])->find();
        $roles = AdminService::getRoleNames($uid);

        if (AdminService::isSuperAdmin($uid)) {
            $buttons = AdminService::SUPPER_PERMISSION;
            $permissions = AdminService::SUPPER_PERMISSION;
        } else {
            $buttons = AdminService::getAuthority($uid, [3]);
            $permissions = AdminService::getAuthority($uid, [1, 2]);
        }

        $data = [
            'user' => $user,
            'roles' => $roles,
            'buttons' => $buttons,
            'permissions' => $permissions,
        ];
        return $this->success($data);
    }

    public function list()
    {
        $username = input('username', '');
        $nickname = input('nickname', '');
        $phone = input('phone', '');
        $login_start = input('login_start', '');
        $login_end = input('login_end', '');
        $pageSize = intval(input('pageSize')) ?: 10;
        $pageNo = intval(input('pageNo')) ?: 1;
        $where = [];
        $username && $where[] = ['username', 'like', "%{$username}%"];
        $phone && $where[] = ['phone', 'like', "%{$phone}%"];
        $nickname && $where[] = ['nickname', 'like', "%{$nickname}%"];
        if ($login_start && $login_end) {
            $where[] = ['login_time', 'between', $login_start, $login_end];
        }

        $count = $this->getModel()
            ->where($where)
            ->count();

        $data = $this->getModel()
            ->where($where)
            ->limit(($pageNo - 1) * $pageSize, $pageSize)
            ->select()
            ->toArray();

        $role_ids = [];
        array_walk($data, function (&$v) use (&$role_ids) {
            $v['role_ids'] = explode(',', $v['role_ids']);
            $role_ids = array_merge($role_ids,  $v['role_ids']);
        });
        $roleMap = SysRole::where('roleId', 'in', $role_ids)
            ->column('roleName', 'roleId');
        array_walk($data, function (&$v) use ($roleMap) {
            $roles = [];
            foreach ($v['role_ids'] as $id) {
                if ($rr = $roleMap[$id] ?? "") {
                    $roles[] = $rr;
                }
            }
            $v['roles'] = $roles;
        });

        return $this->success($this->formatPage($count, $data));
    }

    public function add()
    {
        $data = request()->all();
        $salt = RandomUtil::randomLetter(10);
        $data['password'] = AdminService::getPassword("123456", $salt);
        $data['salt'] = $salt;
        $this->getModel()->insert($data);
        return $this->success();
    }

    public function update()
    {
        $data = request()->all();
        if (isset($data['password']) && $data['password']) {
            $salt = RandomUtil::randomLetter(10);
            $data['password'] = AdminService::getPassword($data['password'], $salt);
            $data['salt'] = $salt;
        }
        $this->getModel()->where('id', '=', $data['id'])->update($data);
        return $this->success();
    }


    public function getById()
    {
        $id = input('id');
        $data = $this->getModel()->withoutField('password')->where('id', '=', $id)->find();
        return $this->success($data);
    }

    public function updateStatus()
    {
        $id = input('id');
        $status = input('status', 0);
        $this->getModel()->where('id', '=', $id)->update([
            'status' => $status
        ]);
        return $this->success();
    }

    public function resetPwd()
    {
        $id = input('id');
        if (!$id) {
            throw new BadException("参数错误");
        }
        $salt = RandomUtil::randomLetter(10);
        $data['password'] = AdminService::getPassword(123456, $salt);
        $data['salt'] = $salt;
        $this->getModel()->where('id', '=', $id)->update($data);
        return $this->success();
    }
}